//
//  FilmTicketBookViewController.m
//  ELife
//
//  Created by  刘奇男 on 11-5-22.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "FilmTicketBookViewController.h"
#import "FilmTicketBookConfirmViewController.h"
#import "FilmHelpViewController.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"
#import "Cinema.h"
#import "AlertView.h"


@implementation FilmTicketBookViewController

@synthesize phoneNumberTextField, ticketCountTextField, cinemaTextField, choseCinema, city, cinemaPicker, chosenCinema, backView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
    [phoneNumberTextField release];
    [ticketCountTextField release];
    [cinemaTextField release];
    
    [choseCinema release];
    [cinemaPicker release]; 
    
    [city release];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    app = [ELifeAppDelegate App];
    
    [cinemaTextField setDelegate:self];
    [ticketCountTextField setDelegate:self];
    [phoneNumberTextField setDelegate:self];

    [cinemaPicker setDelegate:self];
    [cinemaPicker setDataSource:self];
    
    backView.layer.cornerRadius = 8;
    backView.layer.masksToBounds = YES;
    
    
    [self.navigationItem setTitle:@"预订"];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction) next:(id)sender
{
    if ([ticketCountTextField.text length] == 0
        || [phoneNumberTextField.text length] == 0
        || [cinemaTextField.text length] == 0
        ){
        [AlertView showAlert:@"请填写完整"];
        return;
    }
    FilmTicketBookConfirmViewController *controller = [[FilmTicketBookConfirmViewController alloc] initWithNibName:@"FilmTicketBookConfirmView" bundle:nil];
    
    chosenCinema.count = [ticketCountTextField.text intValue];
    chosenCinema.userPhone = phoneNumberTextField.text;
    [controller setCinema:chosenCinema];
    
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}

- (IBAction) help:(id)sender
{
    FilmHelpViewController *controller = [[FilmHelpViewController alloc] initWithNibName:@"FilmHelpView" bundle:nil];
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}

- (IBAction)closeKeypad:(id)sender
{
    [phoneNumberTextField resignFirstResponder];
    [ticketCountTextField resignFirstResponder];
    [cinemaTextField resignFirstResponder];
    
    [sender resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	// the user pressed the "Done" button, so dismiss the keyboard
	[textField resignFirstResponder];
	return YES;
}


-(void) cinemaPickerViewAppare
{
    [self.view addSubview:choseCinema];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)requestCinema
{
    [app showProgressDialog:@"请稍候"];
    
    
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"cinema.php?"]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:2];
    [param setObject:@"get_cinema_list_by_city" forKey:@"action"];
    [param setObject:city forKey:@"city"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [param release];
}
#pragma mark -
#pragma mark 联网回调
- (void)iRequestFinished:(NSData *)response
{    
    [app hideProgressDialog];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];    
    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    
    
    //某个具体节点的文本内容
    GDataXMLElement* cinemasElement = [[bodyElement elementsForName:@"cinemas"]objectAtIndex:0];
    
    NSArray *items = [cinemasElement elementsForName:@"item"];    
    cinemas =  [[NSMutableArray alloc] initWithCapacity:[items count]];
    
    for (int i = 0; i < [items count]; i ++){
        GDataXMLElement *element = [items objectAtIndex:i];
        
        
        NSArray *arr = [element children];
        
        NSString* cinemaName;
        NSInteger cardKindID;
        NSString* cardKindName;
        NSString* cinemaID;
        NSInteger cardKindValue;
        
        for (int j = 0; j<[arr count]; j++) {
            GDataXMLNode *node = [arr objectAtIndex:j];
            
            NSString* key = [node name];
            
            if ([key isEqualToString:@"Cinema"]){
                cinemaName = [node stringValue];
            } else if  ([key isEqualToString:@"CardKindID"]){
                cardKindID = [[node stringValue] intValue];
            } else if  ([key isEqualToString:@"CardKindName"]){
                cardKindName = [node stringValue];                               
            } else if  ([key isEqualToString:@"CinemaID"]){
                cinemaID = [node stringValue];                 
            } else if  ([key isEqualToString:@"CardKindValue"]){
                cardKindValue = [[node stringValue] intValue];
            }
        }
        
        Cinema *cinema = [[[Cinema alloc] init] autorelease];
        cinema.name = cinemaName;
        cinema.cardKindName = cardKindName;
        cinema.cinemaId = cinemaID;
        cinema.cardKindValue = cardKindValue;
        cinema.cardKindId = cardKindID;
        
        [cinemas addObject:cinema];
    }
    [doc release];
    
    [self cinemaPickerViewAppare];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField != cinemaTextField){
        return;
    } 
    
    [phoneNumberTextField resignFirstResponder];
    [ticketCountTextField resignFirstResponder];
    [cinemaTextField resignFirstResponder];
    
    if (cinemas == nil || [cinemas count] == 0){
        [self requestCinema];
    } else {
        [self cinemaPickerViewAppare];
    }
}


- (IBAction) choseCinema:(id)sender
{
    [choseCinema removeFromSuperview];
    
    chosenCinema = [cinemas objectAtIndex:[cinemaPicker selectedRowInComponent:0]];
    
    NSLog(@"ChosenCinema----------------%@\n", chosenCinema.name);
    [cinemaTextField setText:chosenCinema.name];
}

- (IBAction) hideChoseCinema:(id)sender
{
    [choseCinema removeFromSuperview];
}

#pragma mark -
#pragma mark UIPickerViewDataSource

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{			
    Cinema* cinema = [cinemas objectAtIndex:row]; 
	return cinema.name;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
	CGFloat componentWidth = 0.0;
    
    componentWidth = 280;
    
	return componentWidth;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
	return 40.0;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	return [cinemas count];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 1;
}

@end
